<script setup>
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import { changeApi, getUserInfoByIdApi } from '@/api/user';
import { useUserStore } from '@/stores/user';
import { useRoute } from 'vue-router';
import router from '@/router';
import { getUserId } from '@/utils/token';
const isShowUserBtn = ref(false)
const route = useRoute()
const changePasswordForm = reactive({
  newPassword:'',
  confirmNewPassword:''
})
const accountName = ref('admin')
const dialogFormVisible = ref(false)
const formRef = ref(null)
//校验密码
const passwordValid = (rule, value, callback) => {
  if (!value) {
    callback(new Error('密码不能为空'));
  }
  else if (value.length < 8 || value.length > 20) {
    callback(new Error('密码长度必须在8到20位之间'));
  }
  else {
    const hasLetter = /[a-zA-Z]/.test(value);
    const hasNumber = /\d/.test(value);
    const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(value);

    const typesCount = [hasLetter, hasNumber, hasSpecialChar].filter(Boolean).length;

    if (typesCount < 2) {
      callback(new Error('密码必须包含字母、数字和特殊字符中的至少两种'));
    } else {
      callback();
    }
  }
};
const confirmPasswordValid = (rule,value,callback) => {
  if(!value) {
    callback(new Error('确认密码不能为空'))
  }
  else if(value !== changePasswordForm.newPassword) {
    callback(new Error('两次输入密码不一致'))
  }
  else {
    callback()
  }
}

// 得到用户信息
async function getUserInfo() {
  const res = await getUserInfoByIdApi(getUserId())
  accountName.value = res.accountName
}

// 进入页面得到用户信息
onMounted(async () => {
  await getUserInfo()
})
//校验规则
const rules = reactive({
  newPassword:[
    {required:true,message:'请输入新密码',trigger:'blur'},
    {validator:passwordValid,trigger:'blur'}

  ],
  confirmNewPassword:[
    {required:true,message:'请重复新密码',trigger:'blur'},
    {validator:confirmPasswordValid,trigger:'blur'}
  ]
})

// 弹窗关闭时
const handleDialogClose = () => {
  formRef.value.resetFields()
  dialogFormVisible.value = false
}
const useStore = useUserStore()

// 点击确定
const handleSubmitForm = () => {
  formRef.value.validate(async (valid) => {
    if(!valid) {
      ElMessage.error('请输入根据提示正确的内容')
    }else {
      try{
        await changeApi({
          id:useStore.userId,
          password:changePasswordForm.newPassword
        })
        dialogFormVisible.value = false
        ElMessage.success('修改成功,请重新登录')
        useStore.logout()
        router.push('/login')
      }catch(e) {
        ElMessage(e.message)
      }
    }
  })
}
// 请问是否确认退出登录
const confirmLogOut = () => {
  ElMessageBox.confirm(
    '确认退出登录?',
    'Warning',
    {
      confirmButtonText:'确认',
      cancelButtonText:'取消',
      type:'warning',
    }
  ).then(() => {
    useStore.logout()
    router.push('/login')
    ElMessage({
      type:'success',
      message:'退出登录成功,请重新登录'
    })
  })
}
</script>

<template>
  <div class="common-layout">
    <!-- 修改密码的对话框 -->
    <el-dialog v-model="dialogFormVisible" title="修改密码" width="500">
      <el-form :model="changePasswordForm" :rules="rules" ref="formRef">
        <el-form-item label="请输入新密码" prop="newPassword" >
          <el-input v-model="changePasswordForm.newPassword" autocomplete="off" size="large"
          placeholder="请输入新密码" type="password" show-password/>
        </el-form-item>
        <el-form-item label="请重复新密码" prop="confirmNewPassword">
          <el-input v-model="changePasswordForm.confirmNewPassword" autocomplete="off"  size="large"
          placeholder="请重复新密码" type="password" show-password/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" color="#1274b7" @click="handleSubmitForm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-container height="100vh">
      <el-header>
        <div class="header-container">
          <div class="title">
            <h3>HES管理系统后台</h3>
          </div>
          <el-popover
            placement="bottom"
            :width="100"
            trigger="click"
            content=" "
            :popper-style="{minWidth:'50px',padding:'0',width:'auto'}"
            @show="isShowUserBtn = true"
            @hide="isShowUserBtn = false"
          >
            <template #reference>
              <el-button class="user-btn"
              :class="{'user-btn-active':isShowUserBtn}"
              >{{ accountName }}</el-button>
            </template>
            <div class="pop-btn">
              <div>
                <el-button @click="dialogFormVisible=true">修改密码</el-button>
              </div>
              <el-divider />
              <div>
                <el-button @click="confirmLogOut">退出登录</el-button>
              </div>
            </div>
        </el-popover>
        </div>
      </el-header>
      <el-container>
        <el-aside width="200px" height="">
          <el-menu
            :default-active="route.path"
            class="el-menu-vertical-demo"
            router
          >
            <!-- Navigator Two -->
            <el-menu-item index="/main/home">
              <span class="iconfont icon-shouye"></span>
              <span>首页</span>
            </el-menu-item>
            <el-menu-item index="/main/accounts">
              <el-icon><User /></el-icon>
              <span>账户/角色管理</span>
            </el-menu-item>
            <el-sub-menu index="1">
              <template #title>
                <el-icon><Document /></el-icon>
                <span>基础信息管理</span>
              </template>
              <el-menu-item index="/main/emails-service">邮件管理</el-menu-item>
              <el-menu-item index="/main/project-base">项目基础信息管理</el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="2">
              <template #title>
                <!-- <span class="iconfont icon-tongji1"></span> -->
                <el-icon><Setting /></el-icon>
                <span>项目管理</span>
              </template>
              <el-menu-item index="/main/training-program">培训计划管理</el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="3">
              <template #title>
                <span class="iconfont icon-tongji1"></span>
                <span>统计报表</span>
              </template>
              <el-menu-item index="/main/project-stats">项目统计报表</el-menu-item>
              <el-menu-item index="/main/teacher-stats">培训老师统计报表</el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped lang="less">
.common-layout {
  background-color: #f2f0f0;
}
.el-header {
  border-bottom: 1px solid #dad8d8;
  background-color: #ffffff;
}
.el-aside {
  height: 100%;
}
.header-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .user-btn {
    margin-right: 20px;
    border: none;
    font-size: 16px;
    color: black;
    border-radius: 0%;
  }
  .user-btn-active{
    border-bottom:1px solid black ;
  }

}
.pop-btn {
    padding: 10px;
    .el-button {
      border: none;
      font-size: 16px;
      color: black;
    }
    .el-divider--horizontal {
      margin: 5px 0;
    }
  }
.icon-shouye,
.icon-tongji1 {
  display: flex;
  font-size: 16px;
  margin-left: 5px;
  // margin-right: 3px;
  text-align: center;
  vertical-align: middle;
  width: var(--el-menu-icon-width);
  font-weight: 600;
}

.is-vertical {
  height: 100vh;
}

.el-menu {
  border: none;
  padding: 10px;
  height: 100%;
}
.el-dialog {
  .el-form-item {
    display: block;
    ::v-deep .el-form-item__label {
      margin-bottom: 10px;
      color: black;
      font-size: 14px;
    }
  }
}



</style>
